import logging
import time
import schedule
from datetime import datetime

# 调整模块导入路径
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import schedule

from core.spider.pure_api_zero import ApiZeroSeven
from core.util.bf_data_parser import BfDataParser
from db.entity2 import bulk_save_matches
from core.monitor import get_monitor_instance

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("SyncBfData")

def job_sync_bf_data():
    """
    同步比分数据的任务函数
    """
    logger.info("开始同步 BF 数据...")
    start_time = time.time()
    
    try:
        # 1. 获取数据
        api = ApiZeroSeven()
        js_content = api.get_today_match_bf_data()
        if not js_content:
            logger.warning("未能获取到 BF 数据")
            return

        # 2. 解析数据
        parser = BfDataParser()
        parsed_result = parser.parse_js_content(js_content)
        matches_data = parsed_result.get('matches', [])
        
        if not matches_data:
            logger.warning("解析数据为空")
            return
            
        logger.info(f"解析到 {len(matches_data)} 场比赛数据")

        # 3. 转换为 ORM 对象
        orm_objects = parser.convert_to_orm_objects(parsed_result)
        
        # 4. 批量入库
        bulk_save_matches(orm_objects)
        
        # 5. 执行监控检查
        monitor = get_monitor_instance()
        monitor.check_and_update(orm_objects)
        
        duration = time.time() - start_time
        logger.info(f"同步完成，耗时 {duration:.2f} 秒，更新/插入 {len(orm_objects)} 条记录")
        
    except Exception as e:
        logger.error(f"同步过程发生异常: {e}", exc_info=True)

def run_scheduler():
    """
    运行定时任务
    """
    logger.info("启动 BF 数据同步服务")
    
    # 立即执行一次
    job_sync_bf_data()
    
    # 每隔 60 秒执行一次 (比分数据变化较快)
    schedule.every(60).seconds.do(job_sync_bf_data)
    
    while True:
        schedule.run_pending()
        time.sleep(1)

if __name__ == "__main__":
    import sys
    if "--once" in sys.argv:
        job_sync_bf_data()
    else:
        # 检查是否安装了 schedule 库
        try:
            run_scheduler()
        except ImportError:
            logger.error("缺少 schedule 库，请运行 pip install schedule 安装")
            # 如果没有 schedule 库，只运行一次
            job_sync_bf_data()
